package com.itheima.service.Impl;


import com.itheima.mapper.DeptMapper;
import com.itheima.pojo.Dept;
import com.itheima.pojo.DeptLog;
import com.itheima.service.DeptLogService;
import com.itheima.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;



import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;

import java.util.List;


@Slf4j
@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper deptMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    DeptLogService deptLogService;

    /**
     * 查询部门dept
     * @return
     */
    @Override
    public List<Dept> selectDept() {
//        //将查询 缓存到redis里面
//        //1:先查询缓存是否有
//        String select_dept_list = stringRedisTemplate.opsForValue().get(SELECT_DEPT_LIST);
//        //2如果缓存里面拥有 直接将数据返回
//        if (select_dept_list!=null){
//            //如果缓存这个不等于空 则直接返回此缓存
//            //进行序列化操作
//            Dept dept = JSONUtil.toBean(select_dept_list, Dept.class);
//            return Result.success("dept");
//        }
//        //如果等于空 则去查询数据库
//        Result result = deptMapper.selectDept();
//        //查询到了后 缓存到redis里面
//        stringRedisTemplate.opsForValue().set(SELECT_DEPT_LIST,result.toString());
//        return Result.success(result);
        List<Dept> depts = deptMapper.selectDept();
        return depts;
    }

    /**
     * 根据id删除部门id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(Integer id) throws IOException {
        //业务层 可以把id输出出来 删除的
        try {
            log.debug("删除的部门id为:{}"+id);
            //这里是删除 部门的id
            deptMapper.deleteById(id);
            //测试事务问题 如果被包裹住了 则不会触发事务回滚
        if (true){
            throw new IOException("抛出异常了");
        }
            deptMapper.deleteByidEmp(id);
        }finally {
            DeptLog deptLog = new DeptLog();
            deptLog.setCreateTime(LocalDateTime.now());
            deptLog.setDescription("执行了解散部门的操作，此时解散的是"+id+"号部门");
            //调用其他业务类中的方法
            deptLogService.insert(deptLog);
        }
    }

    @Override
    public void insertByName(Dept dept) {
        //补全全部数据
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.insertByName(dept);
    }

    @Override
    public Dept selectById(Integer id) {

        return deptMapper.selectById(id);
    }

    @Override
    public void putByList(Dept dept) {
        //我要把数据全部设置进去
        deptMapper.putByList(dept);
    }


}
